/*
 * http://www-singapore.com/attractions/all-attractions.htm
 */
package managedbean.itinerary;

import entity.ActivityEntity;
import entity.ItinerarySlotEntity;
import exception.ExistException;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import managedbean.PageRedirectorBean;
import org.primefaces.event.DragDropEvent;
import org.primefaces.model.MenuModel;
import session.stateless.ActivitySessionBean;
import session.stateless.ItinerarySessionBean;
import session.stateless.StakeholderSessionBeanStateless;
import session.stateless.SystemMessagesBean;
import session.stateless.TouristAccountSessionBean;
import util.entityhelper.AttractionState;
import util.entityhelper.DailyItineraryState;
import util.entityhelper.StakeholderAccountState;
import util.entityhelper.TripItineraryState;
import util.entityhelper.TouristAccountState;
import util.enumeration.ActivityType;
import util.enumeration.Time24H;
import util.generator.TouristMenuGenerator;
import util.localization.WebLocalization;

/**
 *
 * @author Swee Zhi
 */
@ManagedBean
@RequestScoped
public class ItineraryCreateDailyItineraryActivitiesManagedBean {

    /**
     * @return the selectedSlot
     */
    public ItinerarySlotEntity getSelectedSlot() {
        return selectedSlot;
    }

    /**
     * @param aSelectedSlot the selectedSlot to set
     */
    public void setSelectedSlot(ItinerarySlotEntity aSelectedSlot) {
        selectedSlot = aSelectedSlot;
    }
    @EJB
    private TouristAccountSessionBean touristAccountMgr;
    @EJB
    private ItinerarySessionBean itineraryMgr;
    @EJB
    private StakeholderSessionBeanStateless stakeholderMgr;
    @EJB
    private ActivitySessionBean activityMgr;
    @EJB
    private SystemMessagesBean systemMessages;
    
    // use entity helpers to extract data (attribute extraction and formatting instead of entity in this open bean)
    private TouristAccountState touristAcctState;
    private TripItineraryState itineraryState;
    private AttractionState attractionState;
    
    // fields for this bean
    private FacesContext ctx = FacesContext.getCurrentInstance();
    private WebLocalization localization;
    private PageRedirectorBean redirect;
    
    // use entity helpers to extract data (attribute extraction and formatting instead of entity in this open bean)
    private DailyItineraryState dailyItineraryState;
    
    // fields passed from session
    private Long touristAccountId;
    private String preferredLocale;
    private String itineraryType;
    private Long selectedDailyItineraryId;
    private static List<ItinerarySlotEntity> storedInSessionSelectedList;
    private List<ItinerarySlotEntity> storedInSessionItinerarySlotList;
    private List<ItinerarySlotEntity> storedInSessionItinerarySlotListFromViewDaily;
    private List<AttractionState> storedInSessionAttractionsList;
//    private String statusMessageFromItineraryTravelInfoPage;
    
    // other fields from/to database (+ display)
    private int dayNo;
    private String dayDate;
    private Time24H startTime;
    private Time24H endTime;
    private List<StakeholderAccountState> stakeholdersList; 
    private List<AttractionState> attractionsList;
    private List<ItinerarySlotEntity> droppedItineraryItems;

    
    // fields from XHTML
    private static List<ItinerarySlotEntity> selectedList;
    private static ItinerarySlotEntity selectedSlot;
    
    // display only
    private MenuModel touristMainMenuModel;
    private MenuModel touristNavMenuModel;
    

    /** Creates a new instance of ItineraryCreateDailyItineraryActivitiesManagedBean */
    public ItineraryCreateDailyItineraryActivitiesManagedBean() {
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        
        redirect = new PageRedirectorBean();
        
        /* pre-load values from session and database */
        if (ctx.getExternalContext().getSessionMap().containsKey("touristAccountId")) {
            touristAccountId = (Long) ctx.getExternalContext().getSessionMap().get("touristAccountId");
            // put back the session IDs taken
            ctx.getExternalContext().getSessionMap().put("touristAccountId", touristAccountId);
            
            if (ctx.getExternalContext().getSessionMap().containsKey("itineraryType")) {
                itineraryType = (String) ctx.getExternalContext().getSessionMap().get("itineraryType");
                ctx.getExternalContext().getSessionMap().put("itineraryType", itineraryType);
            }
            
            if (ctx.getExternalContext().getSessionMap().containsKey("selectedDailyItineraryId")) {
                selectedDailyItineraryId = (Long) ctx.getExternalContext().getSessionMap().get("selectedDailyItineraryId");
                ctx.getExternalContext().getSessionMap().put("selectedDailyItineraryId", selectedDailyItineraryId);
            }
            
            // create use only
            if (ctx.getExternalContext().getSessionMap().containsKey("storedInSessionItinerarySlotList")) {
                storedInSessionItinerarySlotList = (List<ItinerarySlotEntity>) ctx.getExternalContext().getSessionMap().get("storedInSessionItinerarySlotList");
            }
            if(selectedList == null)
            {
                selectedList = new ArrayList<ItinerarySlotEntity>(); 
            }
        /*    if (ctx.getExternalContext().getSessionMap().containsKey("storedInSessionSelectedList")) {
                storedInSessionSelectedList = (List<ItinerarySlotEntity>) ctx.getExternalContext().getSessionMap().get("storedInSessionSelectedList");
            }
            */
            if (ctx.getExternalContext().getSessionMap().containsKey("storedInSessionAttractionsList")) {
                storedInSessionAttractionsList = (List<AttractionState>) ctx.getExternalContext().getSessionMap().get("storedInSessionAttractionsList");
            }
        }
        else {
            // redirect back to login
            redirect.goTouristLoginPageAtPreviousLevel();
        }
        /* END load values from session and database */  
    }
    
    public void initView(PhaseEvent event) {
        /* LOCALIZATION */
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        /* END LOCALIZATION */
        
        try {
            itineraryMgr.setSelectedLocale(preferredLocale);
            activityMgr.setSelectedLocale(preferredLocale);
            
            try {
                dailyItineraryState = itineraryMgr.getDailyItineraryByIDReturnByDailyItineraryState(selectedDailyItineraryId);
            }
            catch (ExistException ex) {
//                System.out.println(ex.getMessage());
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getLocalizedMessage(), ""));
            }
            
            dayNo = dailyItineraryState.getDayNo();
            
            if (dayDate == null) {
                dayDate = localization.getLocalizedDateFormat(dailyItineraryState.getDayDate());
            }
            
            if (storedInSessionAttractionsList == null) {
                if (attractionsList == null) {
                    this.attractionsList = new ArrayList<AttractionState>();
                    try {
                        attractionsList = activityMgr.getAttractionsReturnByAttractionState();
                    }
                    catch (ExistException ex) {
                        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getLocalizedMessage(), ""));
                    }
                }
            }
            else {
                attractionsList = storedInSessionAttractionsList;
            }
            
//            if (stakeholdersList == null) {
//                this.stakeholdersList = new ArrayList<StakeholderAccountState>();
//                try {
//                    stakeholdersList = stakeholderMgr.getAllStakeholdersByStakeholderAccountState();
//                }
//                catch (ExistException ex) {
////                    System.out.println(ex.getMessage());
//                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getLocalizedMessage(), ""));
//                }
//                System.out.println("size of stakeholdersList: " + stakeholdersList.size());
//            }
            
          /*  if (storedInSessionSelectedList == null) {
                System.out.println("storedInSessionSelectedList null");
                selectedList = new ArrayList<ItinerarySlotEntity>();
                System.out.println(selectedList.size());
            }
            else {
                System.out.println("storedInSessionSelectedList not null");
                selectedList = storedInSessionSelectedList;
                System.out.println(selectedList.size());
            }
            */
            if (storedInSessionItinerarySlotList == null) {
                droppedItineraryItems = new ArrayList<ItinerarySlotEntity>();
            }
            else {
                droppedItineraryItems = storedInSessionItinerarySlotList;
            }
            
            // main menu 
            TouristMenuGenerator menuGeneratorMain = new TouristMenuGenerator();
            touristMainMenuModel = menuGeneratorMain.generateTouristMainMenu();
            // nav menu
            TouristMenuGenerator menuGeneratorNav = new TouristMenuGenerator();
            touristNavMenuModel = menuGeneratorNav.generateTouristNavMenu();
        }
        catch (Exception ex) {
            ex.printStackTrace();
//            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
        }
    }
    
    public void elementsDropped(DragDropEvent event) {
        System.out.println("in DragDropEvent");
        
        System.out.println("dragID: " + event.getDragId());
        
        String entityName = null;
        String dType = null;
        
        if (event.getDragId().endsWith("attraction")) {
            System.out.println("in Attraction");
            System.out.println(event.getData().toString());
            
            entityName = "Activity";
            dType = "Attraction";
            AttractionState attraction = (AttractionState) event.getData();
            
            ItinerarySlotEntity newItinerarySlot = new ItinerarySlotEntity();
            newItinerarySlot.setEntityName(entityName);
            newItinerarySlot.setdType(dType);
            newItinerarySlot.setItemKey(attraction.getId());
            newItinerarySlot.setActivityType(attraction.getActivityType());
            newItinerarySlot.setActivityName(attraction.getActivityName());
//            newItinerarySlot.setStartTime(newStartTime);
//            newItinerarySlot.setEndTime(newEndTime);
            
            selectedList.add(newItinerarySlot);
            droppedItineraryItems.add(newItinerarySlot);
            attractionsList.remove(attraction);
            
        }
        
        if (event.getDragId().endsWith("stakeholder")) {
            entityName = "Stakeholder";
            System.out.println("in Stakeholder");
            
            entityName = "Stakeholder";
            StakeholderAccountState stakeholder = (StakeholderAccountState) event.getData();
            
            ItinerarySlotEntity newItinerarySlot = new ItinerarySlotEntity();
            newItinerarySlot.setEntityName(entityName);
            newItinerarySlot.setdType(dType);
            newItinerarySlot.setItemKey(stakeholder.getId());
            //TODO: add type to stakeholder too
            newItinerarySlot.setActivityType(ActivityType.DINING);
            newItinerarySlot.setActivityName(stakeholder.getCorpName());
//            newItinerarySlot.setStartTime(newStartTime);
//            newItinerarySlot.setEndTime(newEndTime);
            
            selectedList.add(newItinerarySlot);
            droppedItineraryItems.add(newItinerarySlot);
            stakeholdersList.remove(stakeholder);
            
        }
        
        
//        System.out.println("stakeholdersList size: " + stakeholdersList.size());
        ctx.getExternalContext().getSessionMap().put("storedInSessionItinerarySlotList", droppedItineraryItems);
        //ctx.getExternalContext().getSessionMap().put("storedInSessionSelectedList", selectedList);
        ctx.getExternalContext().getSessionMap().put("storedInSessionAttractionsList", attractionsList);
        
        System.out.println("droppedItems size: " + droppedItineraryItems.size());
        System.out.println("attractionsList size: " + attractionsList.size());
        System.out.println("selectedList size: " + selectedList.size());
    }
    
    public void addItineraryItems(ActionEvent acEvent) {
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        
        try {
            itineraryMgr.setSelectedLocale(preferredLocale);
            
            /* ATTRACTION */
            // reformat time into calendar for calculating purpose in backend
//            Calendar newSTime = new GregorianCalendar();
//            newSTime.setTime(dailyItineraryState.getDayDate());
//            newSTime.set(Calendar.HOUR_OF_DAY, startTime.getTime());
//            Time newStartTime = new Time(newSTime.getTimeInMillis());
//
//            Calendar newETime = new GregorianCalendar();
//            newETime.setTime(dailyItineraryState.getDayDate());
//            newETime.set(Calendar.HOUR_OF_DAY, startTime.getTime());
//            Time newEndTime = new Time(newSTime.getTimeInMillis());
            itineraryMgr.addItineraryItems(selectedDailyItineraryId, droppedItineraryItems);
            System.out.println("selectedDailyItineraryId: " + selectedDailyItineraryId);
            System.out.println("droppedItineraryItems,soze(): " + droppedItineraryItems.size());
            
            String statusMessage = systemMessages.getSystemMessage("ITINERARY_ITEMS_ADDED", preferredLocale);
            ctx.getExternalContext().getSessionMap().put("statusMessageFromEdit", statusMessage);
            redirect.goItineraryViewDailyItineraryPage();
        }
        catch (ExistException ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getLocalizedMessage(), ""));
        }
    }

    public FacesContext getCtx() {
        return ctx;
    }

    public void setCtx(FacesContext ctx) {
        this.ctx = ctx;
    }

    public ItinerarySessionBean getItineraryMgr() {
        return itineraryMgr;
    }

    public void setItineraryMgr(ItinerarySessionBean itineraryMgr) {
        this.itineraryMgr = itineraryMgr;
    }

    public String getItineraryType() {
        return itineraryType;
    }

    public void setItineraryType(String itineraryType) {
        this.itineraryType = itineraryType;
    }

    public WebLocalization getLocalization() {
        return localization;
    }

    public void setLocalization(WebLocalization localization) {
        this.localization = localization;
    }

    public String getPreferredLocale() {
        return preferredLocale;
    }

    public void setPreferredLocale(String preferredLocale) {
        this.preferredLocale = preferredLocale;
    }

    public PageRedirectorBean getRedirect() {
        return redirect;
    }

    public void setRedirect(PageRedirectorBean redirect) {
        this.redirect = redirect;
    }

    public SystemMessagesBean getSystemMessages() {
        return systemMessages;
    }

    public void setSystemMessages(SystemMessagesBean systemMessages) {
        this.systemMessages = systemMessages;
    }

    public Long getTouristAccountId() {
        return touristAccountId;
    }

    public void setTouristAccountId(Long touristAccountId) {
        this.touristAccountId = touristAccountId;
    }

    public TouristAccountSessionBean getTouristAccountMgr() {
        return touristAccountMgr;
    }

    public void setTouristAccountMgr(TouristAccountSessionBean touristAccountMgr) {
        this.touristAccountMgr = touristAccountMgr;
    }

    public TouristAccountState getTouristAcctState() {
        return touristAcctState;
    }

    public void setTouristAcctState(TouristAccountState touristAcctState) {
        this.touristAcctState = touristAcctState;
    }

    public ActivitySessionBean getActivityMgr() {
        return activityMgr;
    }

    public void setActivityMgr(ActivitySessionBean activityMgr) {
        this.activityMgr = activityMgr;
    }

    public AttractionState getAttractionState() {
        return attractionState;
    }

    public void setAttractionState(AttractionState attractionState) {
        this.attractionState = attractionState;
    }

    public TripItineraryState getItineraryState() {
        return itineraryState;
    }

    public void setItineraryState(TripItineraryState itineraryState) {
        this.itineraryState = itineraryState;
    }

    public MenuModel getTouristMainMenuModel() {
        return touristMainMenuModel;
    }

    public void setTouristMainMenuModel(MenuModel touristMainMenuModel) {
        this.touristMainMenuModel = touristMainMenuModel;
    }

    public MenuModel getTouristNavMenuModel() {
        return touristNavMenuModel;
    }

    public void setTouristNavMenuModel(MenuModel touristNavMenuModel) {
        this.touristNavMenuModel = touristNavMenuModel;
    }

    public Long getSelectedDailyItineraryId() {
        return selectedDailyItineraryId;
    }

    public void setSelectedDailyItineraryId(Long selectedDailyItineraryId) {
        this.selectedDailyItineraryId = selectedDailyItineraryId;
    }

    public List<ItinerarySlotEntity> getDroppedItineraryItems() {
        return droppedItineraryItems;
    }

    public void setDroppedItineraryItems(List<ItinerarySlotEntity> droppedItineraryItems) {
        this.droppedItineraryItems = droppedItineraryItems;
    }

    public StakeholderSessionBeanStateless getStakeholderMgr() {
        return stakeholderMgr;
    }

    public void setStakeholderMgr(StakeholderSessionBeanStateless stakeholderMgr) {
        this.stakeholderMgr = stakeholderMgr;
    }

    
    public List<AttractionState> getAttractionsList() {
        return attractionsList;
    }

    public void setAttractionsList(List<AttractionState> attractionsList) {
        this.attractionsList = attractionsList;
    }

    public List<StakeholderAccountState> getStakeholdersList() {
        return stakeholdersList;
    }

    public void setStakeholdersList(List<StakeholderAccountState> stakeholdersList) {
        this.stakeholdersList = stakeholdersList;
    }

    public DailyItineraryState getDailyItineraryState() {
        return dailyItineraryState;
    }

    public void setDailyItineraryState(DailyItineraryState dailyItineraryState) {
        this.dailyItineraryState = dailyItineraryState;
    }

    public String getDayDate() {
        return dayDate;
    }

    public void setDayDate(String dayDate) {
        this.dayDate = dayDate;
    }

    public int getDayNo() {
        return dayNo;
    }

    public void setDayNo(int dayNo) {
        this.dayNo = dayNo;
    }

    public List<ItinerarySlotEntity> getStoredInSessionItinerarySlotList() {
        return storedInSessionItinerarySlotList;
    }

    public void setStoredInSessionItinerarySlotList(List<ItinerarySlotEntity> storedInSessionItinerarySlotList) {
        this.storedInSessionItinerarySlotList = storedInSessionItinerarySlotList;
    }

    public Time24H getEndTime() {
        return endTime;
    }

    public void setEndTime(Time24H endTime) {
        this.endTime = endTime;
    }

    public Time24H getStartTime() {
        return startTime;
    }

    public void setStartTime(Time24H startTime) {
        this.startTime = startTime;
    }

    public List<ItinerarySlotEntity> getSelectedList() {
        return selectedList;
    }

    public void setSelectedList(List<ItinerarySlotEntity> selectedList) {
        this.selectedList = selectedList;
    }

    public List<ItinerarySlotEntity> getStoredInSessionItinerarySlotListFromViewDaily() {
        return storedInSessionItinerarySlotListFromViewDaily;
    }

    public void setStoredInSessionItinerarySlotListFromViewDaily(List<ItinerarySlotEntity> storedInSessionItinerarySlotListFromViewDaily) {
        this.storedInSessionItinerarySlotListFromViewDaily = storedInSessionItinerarySlotListFromViewDaily;
    }

    public List<ItinerarySlotEntity> getStoredInSessionSelectedList() {
        return storedInSessionSelectedList;
    }

    public void setStoredInSessionSelectedList(List<ItinerarySlotEntity> storedInSessionSelectedList) {
        this.storedInSessionSelectedList = storedInSessionSelectedList;
    }
    public void deleteElements()
    {
        this.selectedList.remove(getSelectedSlot());
    }
}
